package com.ai.module.user.service.impl;

import com.ai.module.chat.common.base.ThreadLocalContext;
import com.ai.module.chat.common.domain.BasePage;
import com.ai.module.chat.common.domain.vo.RiskReason;
import com.ai.module.chat.common.enu.MjPrompt;
import com.ai.module.chat.config.advice.exception.BusinessException;
import com.ai.module.business.enu.Source;
import com.ai.module.business.service.BannerRecordService;
import com.ai.module.user.domain.entity.UserPromptEntity;
import com.ai.module.user.domain.vo.UserPromptVo;
import com.ai.module.user.mapper.UserPromptMapper;
import com.ai.module.user.service.UserPromptService;
import com.ai.module.chat.util.aliyun.AliyunUtil;
import com.ai.module.mj.constant.stringConstant.ReturnCode;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import io.github.asleepyfish.service.OpenAiProxyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author: heJinQin
 * @create: 2024-02-22 22:45
 * @description:
 **/
@Slf4j
@Service
public class UserPromptServiceImpl extends ServiceImpl<UserPromptMapper, UserPromptEntity> implements UserPromptService {

    @Autowired
    private OpenAiProxyService openAiProxyService;

    @Autowired
    private BannerRecordService bannerRecordService;
    @Override
    public List<String> midJourneyPromptWords(String message, MjPrompt promptType) {

        // 校验 chat
        RiskReason riskReason = AliyunUtil.getRiskReason(message);
        Boolean success = riskReason.getSuccess();
        if (!success) {
            bannerRecordService.textCheck(String.join(",", riskReason.getRiskWords()),
                    null,
                    message,
                    Source.USER_PROMPT
            );
            log.error("提示词违反相关规则,提示词为[{}]",message);
            throw new BusinessException("提示词违反相关规则", ReturnCode.FAILURE);
        }
        String userId = ThreadLocalContext.getUserId();
//        String content = "你现在是一个midJourney绘画提示词专家，专注于描述场景和人物的细节。请帮我生成一段关于详细描述关于'" + message + "'的绘画提示。结束时，请不要添加任何对画作影响或观者情感的期望描述。";
        String content = promptType.getDesc().replace("&{message}",message);

        ChatCompletionRequest request = ChatCompletionRequest.builder()
                .model("gpt-3.5-turbo")
                .messages(Collections.singletonList(new ChatMessage("user", content)))
                .user("user")
                .temperature(1.0D)
                .topP(1.0D)
                .build();
        request.setMaxTokens(1000);
        List<String> promptList =  openAiProxyService.chatCompletion(request);
        String prompt = promptList.get(0);
        UserPromptEntity userPrompt = new UserPromptEntity();
        userPrompt.setUserContent(message);
        userPrompt.setUserId(userId);
        // 判断是不是 违反规则
        String regex = "(?i)(chatgpt|gpt|openai)";
        // 检查字符串是否匹配
        boolean containsSensitiveWords = prompt.matches(".*" + regex + ".*");
        if (containsSensitiveWords){
            log.error("提示词违反相关规则,提示词为[{}]",prompt);
            throw new BusinessException("提示词违反相关规则", ReturnCode.FAILURE);
        }
        userPrompt.setPrompt(prompt);
        this.save(userPrompt);
        return promptList;
    }

    @Override
    public Page<UserPromptVo> findPrompt(BasePage page) {

        Page<UserPromptVo> userPromptEntityPage = new Page<>(page.getPage(), page.getSize());

        Page<UserPromptVo> userPromptVoIPage = this.baseMapper.findPrompt(userPromptEntityPage,ThreadLocalContext.getUserId());
        List<UserPromptVo> records = userPromptVoIPage.getRecords();
        if (! CollectionUtils.isEmpty(records)){
            Collections.reverse(records);
        }

        return userPromptVoIPage;
    }
}
